import os
import requests
import time
from urllib.parse import urlparse
import hashlib

def download_image(url, filename):
    """下载图片"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        with open(filename, 'wb') as f:
            f.write(response.content)
        print(f"下载成功: {filename}")
        return True
    except Exception as e:
        print(f"下载失败 {url}: {e}")
        return False

def crawl_flower_images():
    """爬取鲜花图片"""
    # 创建图片目录
    image_dir = "../frontend/images/flowers"
    os.makedirs(image_dir, exist_ok=True)
    
    # 鲜花图片URL列表（使用免费的图片资源）
    flower_images = {
        "红玫瑰.jpg": "https://images.unsplash.com/photo-1518895949257-7621c3c786d7?w=800&h=600&fit=crop",
        "粉玫瑰.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "白玫瑰.jpg": "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
        "红康乃馨.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "粉康乃馨.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "白百合.jpg": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
        "粉百合.jpg": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
        "向日葵.jpg": "https://images.unsplash.com/photo-1470509037663-253afd7f0f51?w=800&h=600&fit=crop",
        "红郁金香.jpg": "https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800&h=600&fit=crop",
        "粉郁金香.jpg": "https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800&h=600&fit=crop",
        "满天星.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop"
    }
    
    # 备用图片源（Pixabay免费图片）
    backup_images = {
        "红玫瑰.jpg": "https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg",
        "粉玫瑰.jpg": "https://cdn.pixabay.com/photo/2017/07/21/23/57/rose-2526963_960_720.jpg",
        "白玫瑰.jpg": "https://cdn.pixabay.com/photo/2016/01/05/13/58/rose-1122841_960_720.jpg",
        "红康乃馨.jpg": "https://cdn.pixabay.com/photo/2016/04/12/21/17/flowers-1324438_960_720.jpg",
        "粉康乃馨.jpg": "https://cdn.pixabay.com/photo/2017/02/15/13/40/tulips-2068692_960_720.jpg",
        "白百合.jpg": "https://cdn.pixabay.com/photo/2017/08/05/11/12/lily-2582337_960_720.jpg",
        "粉百合.jpg": "https://cdn.pixabay.com/photo/2016/11/29/05/45/astronomy-1867616_960_720.jpg",
        "向日葵.jpg": "https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072821_960_720.jpg",
        "红郁金香.jpg": "https://cdn.pixabay.com/photo/2017/02/15/13/40/tulips-2068692_960_720.jpg",
        "粉郁金香.jpg": "https://cdn.pixabay.com/photo/2017/02/15/13/40/tulips-2068692_960_720.jpg",
        "满天星.jpg": "https://cdn.pixabay.com/photo/2016/11/29/05/45/astronomy-1867616_960_720.jpg"
    }
    
    print("开始爬取鲜花图片...")
    
    for filename, url in flower_images.items():
        filepath = os.path.join(image_dir, filename)
        
        # 如果文件已存在，跳过
        if os.path.exists(filepath):
            print(f"文件已存在，跳过: {filename}")
            continue
        
        # 尝试下载主要源
        success = download_image(url, filepath)
        
        # 如果失败，尝试备用源
        if not success and filename in backup_images:
            print(f"尝试备用源: {filename}")
            success = download_image(backup_images[filename], filepath)
        
        # 添加延迟避免被限制
        time.sleep(1)
    
    print("图片爬取完成！")

if __name__ == "__main__":
    crawl_flower_images()